// pages/article/detail/detail.js
let common = require('../../../utils/common.js');
Page({
  data: {
    article: {},
    comments: [],
    newTip: '留下几句话吧',
    replyid: 0,
    content: ''
  },
  id: 0,
  skip: 0,
  take: 10,
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.id = options.id;
    this.reqDetail();
  },
  reqDetail: function () {
    let that = this;
    common.asynPost(common.API.article.detail, {
      id: that.id
    }, function (data) {
      if (data['detail']) {
        that.setData({
          article: data['detail']
        });
        that.reqComments();
      }
    });
  },
  reqComments: function () {
    let that = this;
    common.asynPost(common.API.article.comments, {
      articleId: that.id,
      skip: that.skip,
      take: that.take
    }, function (data) {
      that.setData({
        comments: data['comments']
      });
    }, function (err) {
      console.log(err);
    });
  },
  handleNewComment: function (e) {
    // console.log(e.detail.value);
    let that = this, content = e.detail.value.content;
    if (content) {
      common.asynPost(common.API.article.comment_add, {
        openId: '',
        bbsid: that.id,
        parentId: that.data.replyid,
        content: content,
        quoteId: that.data.replyid
      }, function (data) {
        if (data['result']) {
          var temp = that.data.comments, result = data['result'];
          if (that.data.replyid == 0) {
            temp.unshift({
              id: result.id,
              nickName: result.nickName,
              avatar: result.avatar,
              content: content,
              quoteId: that.data.replyid,
              createTime: result.createTime
            });
          } else {
            for (var i = 0, len = temp.length; i < len; i++) {
              if (temp[i].id == that.data.replyid) {
                temp[i].replyComments.push({
                  id: result.id,
                  nickName: result.nickName,
                  avatar: result.avatar,
                  content: content,
                  quoteId: that.data.replyid,
                  createTime: result.createTime
                });
                break;
              }
            }
          }
          that.setData({
            comments: temp,
            content: '',
            newTip: '留下几句话吧',
            replyid: 0,
          });
        }
      });
    }
  },
  handleReply: function (e) {
    let that = this, replyid = e.currentTarget.dataset.id, nickname = e.currentTarget.dataset.nickname;
    that.setData({
      replyid: replyid,
      newTip: '回复@' + nickname
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})